//
//  LGTUserInfoVC.swift
//  KJLGT
//
//  Created by jenkin on 2019/8/16.
//  Copyright © 2019年 jenkin. All rights reserved.
//

import UIKit

class LGTUserInfoVC: LGTBaseVC, UITableViewDelegate, UITableViewDataSource, PhotoDelegate{
    var tableView:UITableView?
    var data:Array<Any>?
    var selectTimeBlock:ClickPostNameModelBlock?
    var citySelectBlock:ZZCityBlock?
    var userModel:UserModel?
    var photoManager:PhotoManager? = {
        let photoManagr1 = PhotoManager()
        return photoManagr1
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setBlock()
    }
    
    override func setUI() {
        super.setUI()
        self.setBavBarStyle(navBarHiden: false, title: "个人信息", back: true)
        self.tableView = UITableView.init(frame: CGRect.init(x: 0.0, y: NavBarH, width: Double(KScreenW), height: Double(KScreenH) - NavBarH), style: UITableView.Style.plain)
        self.view.addSubview(self.tableView!)
        self.tableView?.backgroundColor = ViewBackColor
        self.tableView?.separatorStyle = UITableViewCell.SeparatorStyle.none
        self.tableView?.delegate = self
        self.tableView?.dataSource = self
        self.tableView?.register(LGTUserInfoViewCell.classForCoder(), forCellReuseIdentifier: "cell")
    }
    
    func setBlock(){
        weak var weakSelf = self
        self.reloadBlock = {
            () -> Void in
            weakSelf?.getUserInfo()
        }
        
        self.citySelectBlock = { (data:[Any]?) in
            
            var city:String = ""
            var province:String = ""
            var index = 0
            for i in data ?? []{
                if index == 0{
                    province = i as? String ?? ""
                }else{
                    city = i as? String ?? ""
                }
                index = index + 1
            }
            
            let param:Dictionary = ["province":province, "city":city]
            weakSelf?.updateUserInfo(dict: param)
        }
        
        self.selectTimeBlock = {
            (data:PostNameModel,_ path:IndexPath) in
            print("hello")
            let dateStr:String = data.name ?? ""
            let dateArray:Array<String> = dateStr.components(separatedBy: CharacterSet.init(charactersIn: " "))
            var date:String = ""
            if dateArray.count > 0{
                date = dateArray[0]
            }
            
            let param:Dictionary<String, Any> = ["birthday":date]
            weakSelf?.updateUserInfo(dict: param)
        }
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.data?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
        return self.data?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.data == nil{
            return 0
        }
        
            let data:Array<Any> = self.data?[section] as! Array<Any>
        return data.count
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return SizeFitFloat(10.0)
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView.init()
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return SizeFitFloat(KRate * 44.0)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:LGTUserInfoViewCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! LGTUserInfoViewCell
        let data:Array<Any> = self.data?[indexPath.section] as! Array<Any>
        let dict:Dictionary<String, Any> = data[indexPath.row] as! Dictionary<String, Any>
        cell.data = dict
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: false)
        
        if  indexPath.section == 0{
            if indexPath.row == 0{
                self.selectImage()
            }else{
                let nickNameVC:LGTNickNameVC = LGTNickNameVC()
                nickNameVC.nickName = self.userModel?.nickname ?? ""
                self.navigationController?.pushViewController(nickNameVC, animated: true)
            }
            return
        }
        
        if indexPath.section == 1{
            if indexPath.row == 0{
                self.selectSex()
            }else if indexPath.row == 1{
                let vc:LGTRWZTimeSelectVC = LGTRWZTimeSelectVC()
                vc.modalPresentationStyle = .overCurrentContext
                vc.clickBlock = self.selectTimeBlock
                vc.path = indexPath
                vc.currentDateStr = ""
                vc.isDate = true
                self.navigationController!.present(vc, animated: false, completion: nil)
            }else{
                //ZZCityPickerView.showPick(complete: self.citySelectBlock, superView: self.view)
                let privince:String = self.userModel?.province ?? ""
                let city:String = self.userModel?.city ?? ""
                ZZCityPickerView.showPick(withProvince: privince, city: city, complete: self.citySelectBlock, superView: self.view)
            }
            return
        }

    }
    
    func selectImage(){
        self.photoManager?.delegate = self
        let alertVC = UIAlertController.init(title: "获取方式", message: "", preferredStyle: UIAlertController.Style.actionSheet)
        weak var weakSelf = self
        let playAction = UIAlertAction.init(title: "拍照", style: UIAlertAction.Style.default) { (action) in
            weakSelf?.photoManager?.actionSheet(UIActionSheet(), clickedButtonAt: 0)
        }
        let ablumAction = UIAlertAction.init(title: "从相册中选择", style: UIAlertAction.Style.default) { (action) in
            weakSelf?.photoManager?.actionSheet(UIActionSheet(), clickedButtonAt: 1)
        }
        let cancelAction = UIAlertAction.init(title: "取消", style: UIAlertAction.Style.cancel) { (action) in
            
        }
        alertVC.addAction(playAction)
        alertVC.addAction(ablumAction)
        alertVC.addAction(cancelAction)
        self.present(alertVC, animated: true, completion: nil)
    }
    
    func selectSex(){
        let alertVC = UIAlertController.init(title: "选择性别", message: "", preferredStyle: UIAlertController.Style.actionSheet)
        weak var weakSelf = self
        let playAction = UIAlertAction.init(title: "男", style: UIAlertAction.Style.default) { (action) in
            weakSelf?.updateUserInfo(dict: ["sex":1])
        }
        let ablumAction = UIAlertAction.init(title: "女", style: UIAlertAction.Style.default) { (action) in
            weakSelf?.updateUserInfo(dict: ["sex":2])
        }
        let cancelAction = UIAlertAction.init(title: "取消", style: UIAlertAction.Style.cancel) { (action) in
            
        }
        alertVC.addAction(playAction)
        alertVC.addAction(ablumAction)
        alertVC.addAction(cancelAction)
        self.present(alertVC, animated: true, completion: nil)
    }
    
    func setData(userModel:UserModel){
        var sex:String = ""
        if userModel.sex == 1{
            sex = "男"
        } else if userModel.sex == 2{
            sex = "女"
        }
        
        let city = userModel.city ?? ""
        let province = userModel.province ?? ""
        let data:Array = [
                [
                    ["title":"头像", "icon":userModel.avatar?.url],
                    ["title":"昵称", "text":userModel.nickname]
                ],
                [
                    ["title":"性别",  "text":sex],
                    ["title":"生日", "text":userModel.birthday],
                    ["title":"地址", "text":"\(province) \(city)"]
                ]] as [Any]
        
        self.data = data
        self.tableView?.reloadData()
    }
    
    func updateUserInfo(dict:Dictionary<String, Any>, showMessage:Bool = true){
        weak var weakSelf = self
        LGTHttpUtil.httpUtil.requestData(url: User_Info_Update_URL, param: dict, showMessage: showMessage, success: { (json) in
            weakSelf?.getUserInfo()
        }) { (json) in
            
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.getUserInfo()
    }
    
    func getUserInfo(){
        weak var weakSelf = self
        LGTHttpUtil.httpUtil.requestData(url: User_Info_URL, param: [:], success: { (json) in
            
            let userModel:UserModel = try! lgtDecode(UserModel.self, param: (json["data"] ?? [:]) as! [String : Any])
            weakSelf?.userModel = userModel
            weakSelf?.setData(userModel: userModel)
            
        }) { (json) in
            weakSelf?.showNoData(image: Net_NoData_Image, text: Net_Error_Text, subText: Net_Reload_Text)
        }
    }
    
    //裁剪图片代理
    func imageCropper(_ cropperViewController: VPImageCropperViewController!, didFinished editedImage: UIImage!) {
        
        let image:UIImage = LGTOCBaseUtil.compressOriginalImage(editedImage, to: CGSize.init(width: 600, height: 600))
        let data:Data = image.jpegData(compressionQuality: 1) ?? Data()
        let param:Dictionary<String, Any> = ["image":data]
        weak var weakSelf = self
        LGTHttpUtil.httpUtil.uploadData(url: Upload_Image_URL, param: param, success: { (json) in
            let info:Dictionary<String, Any> = json["data"] as? Dictionary<String, Any> ?? [:]
            let param:Dictionary<String, Any> = ["avatar":info["id"] as? Int ?? ""]
            weakSelf?.updateUserInfo(dict: param)
        }) { (json) in
            
        }
        
         cropperViewController.dismiss(animated: true, completion: nil)
    }
    
    func imageCropperDidCancel(_ cropperViewController: VPImageCropperViewController!) {
        cropperViewController.dismiss(animated: true, completion: nil)
    }
    
    func finish(_ controller: UIViewController!) {
        self.present(controller, animated: true, completion: nil)
    }
    
    func getCropSize() -> CGRect {
        return CGRect.init(x: 0, y: (KScreenH - KScreenW)/2, width: KScreenW, height: KScreenW)
    }
}
